const ts = require('rollup-plugin-typescript2')
const resolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const terser = require('@rollup/plugin-terser')
const pkg = require('./package.json')
const {readFileSync} = require("node:fs");

const banner = [
    '/*!',
    ` * node-action v${pkg.version}`,
    ` * ${pkg.description}`,
    ' * Copyright (c) 会功夫的李白(https://gitee.com/jl15988).',
    ' * This source code is licensed under the MIT license(https://gitee.com/jl15988/node-action/blob/master/LICENSE).',
    ' */'
].join('\n')

function createConfig(options) {
    const config = {
        input: './index.ts',
        type: 'commonjs',
        output: {
            name: 'nodeAction',
            file: options.file,
            format: options.format === 'types' ? 'es' : options.format,
            exports: 'auto',
            banner,
        },
        plugins: [
            // 解析 node 依赖
            // resolve(),
            // 解析 commonjs
            commonjs(),
            // 自定义插件，添加版本
            {
                name: 'setNodeActionVersion',
                load(id) {
                    if (/ActionMain.ts$/.test(id)) {
                        const fileContent = readFileSync(id, 'utf-8')
                        return fileContent.replace('${nodeActionVersion}', pkg.version)
                    }
                }
            },
            // 解析 ts
            ts({
                check: options.format === 'types',
                tsconfigOverride: {
                    compilerOptions: {
                        declaration: options.format === 'types',
                    },
                    exclude: []
                }
            }),
            process.env.BUILD_MINI === 'true' ? terser() : null
        ]
    }

    return config
}

exports.default = [
    createConfig({format: 'cjs', file: pkg.common}),
    createConfig({format: 'es', file: pkg.module}),
    createConfig({format: 'types', file: pkg.typings})
]
